/**
 * @param {Object} src 路径
 * 压缩图片
 */
export const compressImage = (params) => {
	const {
		src,
		quality = 10
	} = params
	return new Promise((resolve, reject) => {
		uni.compressImage({
			src,
			quality,
			fail: (err) => {
				uni.showToast({
					title: '图片压缩失败，请更换Png/Jpg类型图片',
					icon: 'none',
					duration: 5000
				})
				reject(err)
			},
			success: (result) => {
				resolve({
					fileCompressID: result.tempFilePath
				})
			}
		})
	})
}

/**
 * @param {Object} src 路径
 * 上传图片
 */
// 上传指定云环境
// const uniCloudSecond = uniCloud.init({
//   provider: 'aliyun',
//   spaceId: '8602ca35-b43d-4278-ab13-deb4bfba5e10',
//   clientSecret: 'dzw6+ZpICQjCpQ49U/5/eA=='
// });
export const uploadImageItem = async (item, filePath) => {
	if (!filePath) return
	const filename = String(new Date().getTime());
	const fileSuffix = item.name ? item.name : item.path;
	const suffix = /\.[^\.]+$/.exec(fileSuffix)[0]; // 正则表达式，获取文件扩展名
	const cloudPath = filename + suffix;
	const result = await uniCloud.uploadFile({
		cloudPath,
		filePath
	});
	return result
}

/**
 * 上传图片 return { uploadSuccess: true/false, imgCloudPath: string[]}
 */
export const uploadImageList = (carouselImg) => {
	return new Promise(async (resolve) => {
		let imgCloudPath = [];
		let uploadSuccess = true;
		uni.showLoading({
			title: '正在上传...'
		})
		for (let i = 0; i < carouselImg.length; i++) {
			const item = carouselImg[i];
			const result = await uploadImageItem(item, item.path)
			if (!result.success) {
				uploadSuccess = false;
				uni.showToast({
					title: '上传图片异常',
					icon: 'none'
				})
			} else {
				imgCloudPath.push(result.fileID)
			}
		}
		uni.hideLoading()
		resolve({
			uploadSuccess,
			imgCloudPath
		})
	})
}
